'use strict';

const { Surveys, Questions, Answers, UserJoins, SurveyState, Users } = require('../models');
const auth = require('../utils/auth');

let index_fn= async (ctx, next) => {
    ctx.render('index.html');
}

function getTime(time) {
    let date = new Date(time);
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    let d = date.getDate();
    let h = date.getHours();
    let mi = date.getMinutes();

    return (y + '-' + m + '-' + d + ' ' + h + ':' + mi);
};

let createpage_fn = async (ctx, next) => {
    ctx.render('createpage.html');
};

let success_fn = async (ctx, next) => {
    ctx.render('success.html');
};

let survey_fn = async (ctx, next) => {
    let array = [];
    array = ctx.request.body.content;
    let userId = ctx.session.userId;//要改
    let q_theme = ctx.request.body.theme;
    let q_state = ctx.request.body.state;

    let havesurvey =JSON.parse(JSON.stringify(await Surveys.findOne({
        where: {
            userId: userId,
            surveyTheme: q_theme,
            isDelete: 0
        }
    }))) ;

    if (havesurvey === null) {
        if (q_theme.trim().length > 0) {
            if (q_state.trim().length > 0) {
                await Surveys.create({
                    userId: userId,
                    surveyTheme: q_theme,
                    surveyState: q_state
                });

                let survey = await Surveys.findOne({
                    where: {
                        userId: userId,
                        surveyTheme: q_theme,
                        surveyState: q_state
                    }
                });

                for (var r = 1; r <= array.length; r++) {
                    await Questions.create({
                        serveyId: survey.id,
                        questionNumber: r,
                        questionContent: array[r - 1]
                    });
                };

                await SurveyState.create({
                    surveyId: survey.id,
                });

                ctx.body = { code: 200, msg: "保存成功" };
            } else {
                ctx.body = { code: 400, msg: "说明不能为空" };
            }
        } else {
            ctx.body = { code: 400, msg: "主题不能为空" };
        }
    } else {
        ctx.body = { code: 400, msg: "问卷不能重复创建" };
    }

};

let surveypage_fn = async (ctx, next) => {
    let surveyId = ctx.params.id;
    ctx.session.surveyId = surveyId;
    console.log("第一个"+ctx.session.surveyId);
    console.log("第二个"+ctx.session["surveyId"]);

    let surveys = JSON.parse(JSON.stringify(await Surveys.findOne({
        where: {
            id: surveyId
        }
    })));

    let questions = JSON.parse(JSON.stringify(await Questions.findAll({
        where: {
            serveyId: surveys.id
        }
    })));

    let obj = {
        questions,
        surveys
    };

    ctx.render('surveypage.html', obj);
};

let answer_fn = async (ctx, next) => {
    let scoreArr = [];
    scoreArr = ctx.request.body.scoreAll;
    let surveyId = ctx.session.surveyId;//要改
    let userId = ctx.session.userId;

    console.log(scoreArr);
    console.log(surveyId);
    console.log(userId);

    let user = await UserJoins.findOne({
        where: {
            userId: userId,
            surveryId: surveyId
        }
    });

    let userNull = JSON.parse(JSON.stringify(user));

    if (userNull === null) {
        for (var i = 0; i < scoreArr.length; i++) {
            await Answers.create({
                surveryId: surveyId,
                userId: userId,
                questionNumber: i + 1,
                score: scoreArr[i]
            });
        };

        await UserJoins.create({
            userId: userId,
            surveryId: surveyId
        });

        ctx.body = { code: 200, msg: "保存成功" };
    } else {
        ctx.body = { code: 400, msg: "您已填写本问卷，不可重复填写问卷" };
    };

};

let surveyAll_fn = async (ctx, next) => {
    let userId = ctx.session.userId;//要改
    let username = ctx.session.userName;
    let surveyArr = [];
    let surveys = JSON.parse(JSON.stringify(await Surveys.findAll({
        where: {
            userId: userId,
            isDelete: 0
        }
    })));

    surveys.forEach(item => {
        item.updatedTime = getTime(JSON.parse(item.updatedAt)); 
        surveyArr.push(item.id);
    });


    let surveystate = JSON.parse(JSON.stringify(await SurveyState.findAll({
        where: {
            surveyId: surveyArr
        }
    })));

    surveys.forEach(item => {
        let stateInfo = surveystate.filter(element => {
            return item.id === element.surveyId;
        })[0];

        if (stateInfo.state === "0") {
            item.stateName = "未发布";
        } else {
            item.stateName = "已发布";
        }
    })


    let obj = {
        surveys,
        username
    };

    ctx.render('surveyAll.html', obj);
}

let surveypageJudge_fn = async (ctx, next) => {
    let surveyId = ctx.request.body.surveyId;
    ctx.session.surveyId = surveyId;

    let obj = {
        code: 200,
        id: surveyId
    };
    ctx.body = obj;
};

let survey_remove_fn = async (ctx, next) => {
    let removeId = ctx.request.body.removeId;

    await Surveys.update({ isDelete: 1 }, {
        where: {
            id: removeId
        }
    });

    await SurveyState.update({ isDelete: 1 }, {
        where: {
            id: removeId
        }
    });

    ctx.body = { code: 200, msg: '删除成功' }
}


let update_judge_fn = async (ctx, next) => {
    let surveyId = ctx.request.body.currentId;
    ctx.session["surveyId"] = surveyId;

    let obj = {
        code: 200,
        id: surveyId
    };
    ctx.body = obj;
}


let update_page_fn = async (ctx, next) => {
    let surveyId = ctx.session["surveyId"];

    let surveys = JSON.parse(JSON.stringify(await Surveys.findOne({
        where: {
            id: surveyId
        }
    })));

    let question = JSON.parse(JSON.stringify(await Questions.findAll({
        where: {
            serveyId: surveyId
        }
    })));

    let obj = {
        surveys,
        question,
        surveyId
    }
    ctx.render("updateSurvey.html", obj);
}

let surveypage_update_fn = async (ctx, next) => {
    let array = [];
    array = ctx.request.body.content;
    let userId = ctx.session.userId;//要改
    let q_theme = ctx.request.body.theme;
    let q_state = ctx.request.body.state;
    let surveyId = ctx.request.body.currentId;
    let numberArr = [];//存放questionNumber

    if (q_theme.trim().length > 0) {
        if (q_state.trim().length > 0) {
            await Surveys.update({ surveyTheme: q_theme, surveyState: q_state }, {
                where: {
                    id: surveyId
                }
            });

            let question = JSON.parse(JSON.stringify(
                await Questions.findAll({
                    where: {
                        serveyId: surveyId
                    }
                })));

            //给一个判断question中原有的数据长度和新数据的长度作比较，如果question长度大于array长度，则删除queestion多余数据，如果array大于question长度，则添加多余数据
            question.forEach(item => {
                numberArr.push(item.questionNumber);
            });

            if (numberArr.length > array.length) {
                //    question长度大于array长度，则删除queestion多余数据
                for (var i = 1; i <= array.length; i++) {
                    await Questions.update({ questionContent: array[i - 1] }, {
                        where: {
                            questionNumber: i
                        }
                    });
                };

                for (var a = array.length; a <= numberArr.length; a++) {
                    await Questions.destroy({
                        where: {
                            questionNumber: a + 1
                        }
                    });
                }

                ctx.body = { code: 200, msg: "保存成功" };

            } else if (numberArr.length === array.length) {
                for (var i = 1; i <= array.length; i++) {
                    await Questions.update({ questionContent: array[i - 1] }, {
                        where: {
                            questionNumber: i
                        }
                    });
                };
                ctx.body = { code: 200, msg: "保存成功" };


            } else if (array.length > numberArr.length) {
                // 如果array大于question长度，则添加多余数据
                for (var i = 1; i <= array.length; i++) {
                    await Questions.update({ questionContent: array[i - 1] }, {
                        where: {
                            questionNumber: i
                        }
                    });
                };

                for (var a = numberArr.length; a < array.length; a++) {
                    console.log(array[a]);
                    await Questions.create({
                        serveyId: surveyId,
                        questionNumber: a,
                        questionContent: array[a]
                    });
                }
                ctx.body = { code: 200, msg: "保存成功" };
            }
            ctx.body = { code: 200, msg: "保存成功" };

        } else {
            ctx.body = { code: 400, msg: "说明不能为空" };
        };
    } else {
        ctx.body = { code: 400, msg: "主题不能为空" };
    };
}

let sendpage_fn = async (ctx, next) => {
    let surveyId = ctx.session.surveyId;

    console.log(surveyId);

    let surveys = JSON.parse(JSON.stringify(await Surveys.findOne({
        where: {
            id: surveyId
        }
    })));

    let questions = JSON.parse(JSON.stringify(await Questions.findAll({
        where: {
            serveyId: surveys.id
        }
    })));

    let surveystate = JSON.parse(JSON.stringify(await SurveyState.findOne({
        where: {
            id: surveyId
        }
    })));

    console.log(surveystate);
    let obj = {
        questions,
        surveys,
        surveystate
    };

    ctx.render('surveyNoSend.html', obj);
};

let survey_send_fn = async (ctx, next) => {
    let surveyId = ctx.session.surveyId;
    let time = Date.now();
    await SurveyState.update({ state: 1,updatedAt:time }, {
        where: {
            surveyId: surveyId
        }
    });

    ctx.body = { code: 200, msg: "发布成功" }
}

let published_fn = async (ctx, next) => {
    let userId = ctx.session.userId;
    let surveyArr = [];

    let surveystate = JSON.parse(JSON.stringify(await SurveyState.findAll({
        where: {
            state: 1
        }
    })));

    surveystate.forEach(item => {

        surveyArr.push(item.surveyId);
    });


    let surveys = JSON.parse(JSON.stringify(await Surveys.findAll({
        where: {
            id: surveyArr,
            userId: userId,
            isDelete: 0
        }
    })));


    console.log(JSON.stringify(surveys) === "[]");

    if (JSON.stringify(surveys) === "[]") {
        ctx.render("published.html", { msg: "无问卷" });
    } else {
        surveys.forEach(item => {
            surveystate.filter(element => {
                return item.id === element.surveyId;
            })[0];
            item.stateName = "已发布";
            item.updatedTime = getTime(JSON.parse(item.updatedAt));
        })

        let obj = {
            surveys
        };

        ctx.render("published.html", obj);
    }
}

let unpublished_fn = async (ctx, next) => {
    let userId = ctx.session.userId;
    let surveyArr = [];

    let surveystate = JSON.parse(JSON.stringify(await SurveyState.findAll({
        where: {
            state: 0
        }
    })));

    surveystate.forEach(item => {
        surveyArr.push(item.surveyId);
    });


    let surveys = JSON.parse(JSON.stringify(await Surveys.findAll({
        where: {
            id: surveyArr,
            userId: userId,
            isDelete: 0
        }
    })));


    console.log(JSON.stringify(surveys) === "[]");

    if (JSON.stringify(surveys) === "[]") {
        ctx.render("unpublished.html", { msg: "无问卷" });
    } else {
        surveys.forEach(item => {
            item.stateName = "未发布";
            item.updatedTime = getTime(JSON.parse(item.updatedAt));
        })

        let obj = {
            surveys
        };

        ctx.render("unpublished.html", obj);
    }
}

let surveyGruond_fn = async (ctx, next) => {
    let surveyArr = [];
    let surveystate = JSON.parse(JSON.stringify(await SurveyState.findAll({
        where: {
            state: 1
        } 
    })));

    surveystate.forEach(item => {
        surveyArr.push(item.surveyId);
    });

    let user = JSON.parse(JSON.stringify(await Users.findAll({
        where: {
            role: 1
        }
    })));

    let surveys = JSON.parse(JSON.stringify(await Surveys.findAll({
        where: {
            id: surveyArr,
            isDelete: 0,
        }
    })));

    
    let userjoin = JSON.parse(JSON.stringify(await UserJoins.count({
        where: {
            surveryId: surveyArr
        },
        attributes: ['surveryId'],
        group: 'surveryId',
    })));

    surveys.forEach(item => {
        let u = user.filter(element => {
            return element.id === item.userId;
        })[0];

        let join = userjoin.filter(num => {
            return num.surveryId === item.id
        })[0];

        item.usercount = join === undefined ? 0 : join.count

        item.name = u === undefined ? '匿名' : u.username;
        item.updatedTime = getTime(JSON.parse(item.updatedAt));
    })

    let obj = {
        surveys
    };
    ctx.render("surveyGround.html", obj);
} 


let publish_question_fn = async (ctx, next) => {
    let id = ctx.params.id;
    let userIdArr = [];
    let questionNum = [];

    let question = JSON.parse(JSON.stringify(await Questions.findAll({
        where: {
            serveyId: id
        }
    })));

    let answer = JSON.parse(JSON.stringify(await Answers.findAll({
        where: {
            surveryId: id
        }

    })));

    answer.forEach(item => {
        questionNum.push(item.questionNumber)
        userIdArr.push(item.userId);
    });


    let newArr = [];
    for (var i = 0; i < userIdArr.length; i++) {
        if (newArr.indexOf(userIdArr[i]) === -1) {
            newArr.push(userIdArr[i]);
        }
    };

    let user = JSON.parse(JSON.stringify(await Users.findAll({
        where: {
            id: newArr
        }
    })));


    let sumList = [];
    user.forEach(u => {
        let answers = answer.filter(a => {
            return a.userId === u.id
        });
        // 得分情况


        let sum = 0;
        answers.forEach(item => {
            let num = parseInt(item.score)
            sum += num
        })
        sumList.push(sum)

        u.answers = answers;
        u.count = sum
    })



    let obj = {
        question,
        answer,
        user,

    }
    ctx.render("surveyData.html",obj);
}

module.exports = {
    '/': ['get',auth, index_fn],
    '/createpage': ['get', auth, createpage_fn], //创建问卷页面
    '/success': ['get', success_fn],
    '/surveypage/:id': ['get', auth, surveypage_fn],// 用户填写问卷页面
    '/surveypage/judge': ['post', auth, surveypageJudge_fn], //查看问卷页面，保存问卷id
    '/question': ['post', survey_fn], //创建问卷，将创建问卷数据和问题数据
    '/question/answer': ['post', answer_fn], //用户填写问卷后创建数据
    '/surveyAll': ['get', auth, surveyAll_fn], //所有问卷的页面
    '/surveypage/remove': ['post', survey_remove_fn],//删除问卷
    '/surveypage/update/:id': ['get', auth, update_page_fn], // 编辑问卷页面
    '/surveypage/updateJudge': ['post', update_judge_fn],// 获取编辑问卷id
    '/surveypage/updatedata': ['post', surveypage_update_fn],//编辑问卷更新数据
    '/survey/send': ['post', survey_send_fn], //发布问卷
    '/survey/sendpage/:id': ['get', sendpage_fn], // 获取发布问卷页面
    '/published': ['get', auth, published_fn], //已发布问卷集合
    '/unpublished': ['get', auth, unpublished_fn],// 未发布问卷集合
    '/surveyGround': ['get', auth, surveyGruond_fn],//问卷广场
    '/survey/datapage/:id':['get',auth,publish_question_fn]
}